'use client'

import { FaUser } from 'react-icons/fa'
import { useRouter } from 'next/navigation'
import { ExitIcon } from '@radix-ui/react-icons'

import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
import LogoutButton from '@/components/auth/logout-button'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'

import { cn } from '@/lib/utils'
import { useCurrentUser } from '@/hooks/use-current-user'

type UserButtonProps = {
    className?: string
}

const UserButton = ({ className }: UserButtonProps) => {
    const user = useCurrentUser()
    const router = useRouter()

    return (
        user ? (
            <DropdownMenu>
                <DropdownMenuTrigger className={cn(className)}>
                    <Avatar className='h-9 w-9 p-[2px] border'>
                        <AvatarImage src={user?.image || ''} />
                        <AvatarFallback className='bg-sky-500'>
                            <FaUser className='text-white' />
                        </AvatarFallback>
                    </Avatar>
                </DropdownMenuTrigger>
                <DropdownMenuContent className='w-40' align='end'>
                    <LogoutButton>
                        <DropdownMenuItem>
                            <ExitIcon className='w-4 h-4 mr-2' />
                            退出
                        </DropdownMenuItem>
                    </LogoutButton>
                </DropdownMenuContent>
            </DropdownMenu >
        ) : (
            <div
                className='border rounded-md flex items-center justify-between px-2 py-1 cursor-pointer hover:border-primary'
                onClick={() => {
                    router.push('/auth/login')
                }}
            >
                <FaUser className='w-3 h-3 mr-2 text-primary' />
                <span className='text-sm text-muted-foreground'>登录</span>
            </div>
        )
    )
}

export default UserButton